package fon.rm2.client.wifi;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import fon.rm2.client.R;

public class WiFiActivity extends Activity{
	
	private static final String TAG = "WiFiActivity";
	
	TextView txtAvailableNetworks;
	Button btnScan, btnStopWifiActivity;
	
	WifiManager wifi;
	BroadcastReceiver receiver;
	
	ListView lstAvailableNetworks = null;
	
	StringBuffer strBuff = null;
	
	WiFiAP selectedNetwork = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	try
    	{    	
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.wifi);
	        
	        lstAvailableNetworks = (ListView) findViewById(R.id.lstAvailableNetworks);
	        
	        initWiFi();
	        
	        txtAvailableNetworks = (TextView) findViewById(R.id.txtAvailableNetworks);
	        btnScan = (Button) findViewById(R.id.btnScan);
	        btnScan.setOnClickListener(new View.OnClickListener() 
	        {
				
				@Override
				public void onClick(View view) {
					initWiFi();
					if (view.getId() == R.id.btnScan) {
						Log.d(TAG, "onClick() wifi.startScan()");
						wifi.startScan();
					}
				}
	        });
	        
	        btnStopWifiActivity = (Button) findViewById(R.id.btnStopWifiActivity);
	        btnStopWifiActivity.setOnClickListener(new View.OnClickListener() 
	        {	
				@Override
				public void onClick(View view) {
					finish();
				}
	        });
	        
	        if (receiver == null )
	        	receiver = new WiFiScanReceiver(this);
	        
	        
	        registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    	}
    	catch(Exception ex)
    	{
    		Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
    	}
    }
    
    @SuppressWarnings("unused")
	private void showAvailableNetworks()
    {
    	try
    	{
	    	strBuff = new StringBuffer();
	        WifiInfo wifiInfo = wifi.getConnectionInfo();

        	int ipAddress = wifiInfo.getIpAddress();
	        
	        String ipAddr = String.format("%d.%d.%d.%d",
	        		(ipAddress & 0xff),
	        		(ipAddress >> 8 & 0xff),
	        		(ipAddress >> 16 & 0xff),
	        		(ipAddress >> 24 & 0xff));
	        
	        strBuff.insert(0, "\nIp address: " + ipAddr);
	        strBuff.append("\n\nWiFi Status: " + wifiInfo.toString());
	        
	        java.util.List<WifiConfiguration> lstWifiConfig = wifi.getConfiguredNetworks();
	        for(WifiConfiguration wfcfg : lstWifiConfig )
	        	strBuff.append("\n\n" + wfcfg.SSID);
	        
	        txtAvailableNetworks.setText(strBuff.toString());
    	}
    	catch(Exception ex)
    	{
    		Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
    	}
    }


    public void showAvailableNetworks(List<ScanResult> listOfAvalableNetworks)
    {
    	try
    	{    		
    		ArrayList<WiFiAP> arrayListAPs = new ArrayList<WiFiAP>();
    		
    		for(ScanResult res : listOfAvalableNetworks)
    		{
    			arrayListAPs.add(new WiFiAP(res));
    		}
    		
    		lstAvailableNetworks.setAdapter(new ArrayAdapter<WiFiAP>(this, android.R.layout.simple_list_item_1, 
    				arrayListAPs));
    		
    		lstAvailableNetworks.setTextFilterEnabled(true);
    		lstAvailableNetworks.setOnItemClickListener( new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View v,
						int position, long id) {

					selectedNetwork = (WiFiAP)lstAvailableNetworks.getItemAtPosition(position);
					AlertDialog.Builder alert = new AlertDialog.Builder(WiFiActivity.this);
					alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							
							String wantedSSID = selectedNetwork.getSSID();
							WifiInfo wifiInfo = wifi.getConnectionInfo();
							String currentSSID = "";
							java.util.List<WifiConfiguration> lstWifiConfig = wifi.getConfiguredNetworks();
							String selectedCapabilities = selectedNetwork.getCapabilities();
							
							
							if( wifiInfo.getNetworkId() != -1 )
								currentSSID = wifiInfo.getSSID();

				        	if(currentSSID.equals(wantedSSID))
				        	{
				        		Toast.makeText(WiFiActivity.this, R.string.msg_already_connected_to_wanted_wifi, Toast.LENGTH_LONG).show();
				        		return;
				        	}		
				        					        	
				        	wantedSSID = "\"" + wantedSSID + "\"";
							
					        for(WifiConfiguration wfcfg : lstWifiConfig )
					        {						        	
								if(wfcfg.SSID.equals(wantedSSID))
								{
									if(selectedCapabilities.contains("WEP"))
										if(wfcfg.wepKeys[0] == null && wfcfg.wepKeys[1] == null && wfcfg.wepKeys[2] == null && 
												wfcfg.wepKeys[3] == null)
										{
											wifi.removeNetwork(wfcfg.networkId);
											continue;
										}
									
									if(selectedCapabilities.equals("") || selectedCapabilities.contains("WEP"))
									{									
										Toast.makeText(WiFiActivity.this, R.string.msg_ssid_found_in_system, Toast.LENGTH_SHORT).show();
										if (wifi.enableNetwork(wfcfg.networkId, true))
											Toast.makeText(WiFiActivity.this, R.string.msg_connection_success, Toast.LENGTH_SHORT).show();
										else
											Toast.makeText(WiFiActivity.this, R.string.msg_connection_failiure, Toast.LENGTH_SHORT).show();
										return;
									}
								}								
					        }				        	
				        	
					        if(selectedCapabilities.equals(""))
					        {
					        	WifiConfiguration wfc = new WifiConfiguration();
					        	wfc.SSID = wantedSSID;
					        	wfc.status = WifiConfiguration.Status.DISABLED;
					        	wfc.priority = 40;
					        	
					        	wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
					        	wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
					        	wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
					        	wfc.allowedAuthAlgorithms.clear();
					        	wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
					        	wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
					        	wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
					        	wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
					        	wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
					        	wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
					        	
					        	int netId = wifi.addNetwork(wfc);
					        	if( wifi.enableNetwork(netId, true) )
					        		Toast.makeText(WiFiActivity.this, R.string.msg_connection_success, Toast.LENGTH_SHORT).show();
					        	else
					        		Toast.makeText(WiFiActivity.this, R.string.msg_connection_failiure, Toast.LENGTH_SHORT).show();
					        	
					        	return;
					        }
					        
					        if(selectedCapabilities.contains("WEP"))
					        {
					        	AlertDialog.Builder builder;

					        	Context mContext = WiFiActivity.this;
					        	LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
					        	View layout = inflater.inflate(R.layout.wep_password_dialog,
					        	                               (ViewGroup) findViewById(R.id.wep_password_layout_root));

					        	final TextView txtWepPassword = (TextView) layout.findViewById(R.id.txtWepPassword);
					        	final CheckBox chkIsHexString= (CheckBox) layout.findViewById(R.id.chkIsHexString);
					        
					        	builder = new AlertDialog.Builder(mContext);
					        	builder.setView(layout);
					        	
					        	builder.setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										
										String password = txtWepPassword.getText().toString();
										
										WifiConfiguration wfc = new WifiConfiguration();
		
							        	wfc.SSID = "\"".concat(selectedNetwork.getSSID()).concat("\"");
							        	wfc.status = WifiConfiguration.Status.DISABLED;
							        	wfc.priority = 40;
		
							        	
							        	wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
							        	wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
							        	wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
							        	wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
							        	wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
							        	wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
							        	wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
							        	wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
							        	wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
		
							        	if (chkIsHexString.isChecked()) 
							        		wfc.wepKeys[0] = password;
							        	else 
							        		wfc.wepKeys[0] = "\"".concat(password).concat("\"");
							        	
							        	wfc.wepTxKeyIndex = 0;			
							        	
							        	int netId = wifi.addNetwork(wfc);
							        	if( wifi.enableNetwork(netId, true) )
							        		Toast.makeText(WiFiActivity.this, R.string.msg_connection_success, Toast.LENGTH_SHORT).show();
							        	else
							        		Toast.makeText(WiFiActivity.this, R.string.msg_connection_failiure, Toast.LENGTH_SHORT).show();
							        	return;							        								        	
									}
								});
					        	
					        	builder.setNegativeButton(R.string.btn_cancel, null);					        						        	
					        	builder.show();			
					        }
					        else
					        	if(selectedCapabilities.contains("WPA") || selectedCapabilities.contains("PSK") 
					        			|| selectedCapabilities.contains("IBSS") || selectedCapabilities.contains("TKIP")
					        			|| selectedCapabilities.contains("CCMP"))
					        		Toast.makeText(WiFiActivity.this, R.string.err_msg_security_alg_not_supported, Toast.LENGTH_LONG).show();
						}
					});
					
					alert.setNegativeButton("No", null);
					
					alert.setMessage("Are you sure you want to connect to " + selectedNetwork);
					alert.show();
				}
			});
    	}
    	catch(Exception ex)
    	{
    		Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
    	}
    }
    
    private void initWiFi()
    {
    	try
    	{
    		if(wifi == null)
    			wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    	}
    	catch(Exception ex)
    	{
    		Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
    	}
    }
    
    @Override
    protected void onStop() {
    	try
    	{
    		unregisterReceiver(receiver);
    		super.onStop();
    	}
    	catch(Exception ex)
    	{
    		Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
    	}
    }
    
    public WifiManager getWifi()
    {
    	return wifi;
    }
}